package org.wiztools.awsabstraction;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.google.inject.name.Names;
import com.mycila.inject.jsr250.Jsr250;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 * @author subwiz
 */
public final class APIClient {
    
    static final String CONFIG_DIR_SYS_PROP = "configDir";
    
    private static final Module module = new AbstractModule() {
        @Override
        protected void configure() {
            try {
                Properties props = new Properties();
                final String configDirStr = System.getProperty(CONFIG_DIR_SYS_PROP);
                final File configDir = new File(configDirStr);
                final File[] configs = configDir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        if(pathname.isFile()
                                && pathname.getName().endsWith(".properties")) {
                            return true;
                        }
                        return false;
                    }
                });
                for(File config: configs) {
                    try(InputStream is = new FileInputStream(config);) {
                        props.load(is);
                    }
                }
                Names.bindProperties(binder(), props);
            }
            catch(IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    
    private static final Injector injector;
    static {
        injector =  Guice.createInjector(Stage.PRODUCTION,
                Jsr250.newJsr250Module(),
                module);
    }
    
    /**
     * 
     * @param <T> The type of class that needs to be instantiated.
     * @param c The instance of the class requested.
     * @return The instantiated class.
     */
    public static <T> T getInstance(Class<T> c) {
        return injector.getInstance(c);
    }
}
